/*
 * Funambol is a mobile platform developed by Funambol, Inc.
 * Copyright (C) 2008 Funambol, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
 * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA.
 *
 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by Funambol" logo. If the display of the logo is not reasonably
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by Funambol".
 */

#import <UIKit/UIKit.h>

#import "common.h"
#import "MainSingleView.h"
#import "AccountView.h"
#import "SettingsSingleView.h"
#import "base/Log.h"
#import "UIController.h"
#import "FunambolAPI.h"
#include <time.h>
#import "customs.h"
#include "TimeUtils.h"

@implementation MainSingleView

- (id)init {
    
    syncContactText = nil;
    self = [super init];
	if (self)
	{
		// this title will appear in the navigation bar
		self.title = NSLocalizedString(@"AppName",@"Funambol");
		menuList = [[NSMutableArray alloc] init];
	}
	return self;
}

- (void) loadView{
    UIView *contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
	self.view = contentView;
	[contentView release];
    
    SettingsSingleView* settingsview = [[SettingsSingleView alloc]init];
    [menuList addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
                         NSLocalizedString(@"Settings", @""), @"title",
                         settingsview, @"viewController",
                         nil]];
    [settingsview release];
    
    NSString* URL;
    NSString* username;
    NSString* password; 
    
    [[FunambolAPI getInstance] loadSyncConfig:&URL username:&username password:&password];
    
    if([username isEqualToString:@""] || [password isEqualToString:@""]){
        AccountView* accountview = [[AccountView alloc]init];
        [[self navigationController] pushViewController:accountview animated:NO];
        
    }
    StringBuffer urlstring([URL UTF8String]);
    if((urlstring.find(" ") != StringBuffer::npos)||
       (urlstring.find("<") != StringBuffer::npos)||
       (urlstring.find(">") != StringBuffer::npos)){
        AccountView* accountview = [[AccountView alloc]init];
        [[self navigationController] pushViewController:accountview animated:NO];
    } 
    
    [URL      release];
    [username release];
    [password release];
	
    [self addComponents];
}

- (void) viewDidAppear:(BOOL)animated{
    NSString* URL;
    NSString* username;
    NSString* password; 
    
    [[FunambolAPI getInstance] loadSyncConfig:&URL username:&username password:&password];
    
    if([username isEqualToString:@""] || [password isEqualToString:@""]){
        AccountView* accountview = [[AccountView alloc]init];
        [[self navigationController] pushViewController:accountview animated:YES];

    }
    StringBuffer urlstring([URL UTF8String]);
    if((urlstring.find(" ") != StringBuffer::npos)||
       (urlstring.find("<") != StringBuffer::npos)||
       (urlstring.find(">") != StringBuffer::npos)){
        AccountView* accountview = [[AccountView alloc]init];
        [[self navigationController] pushViewController:accountview animated:YES];
    } 
    
    [URL      release];
    [username release];
    [password release];
}

- (void) reload {
    
}

- (void)addComponents {
	
	large_font = [UIFont boldSystemFontOfSize:24];
	small_font = [UIFont systemFontOfSize:12];
	medium_font = [UIFont systemFontOfSize:15];
    idx = 0;
    
    [self.view setBackgroundColor:[UIColor whiteColor]];

    //Add the main button image
    background =  [[UIImageView alloc] initWithFrame: CGRectMake(12.5f, 20.0f, 295.0f, 295.0f)];
    [background setImage:[UIImage imageNamed: @"button_syncing.png"]];
     
    [self.view addSubview:background];
    
    contactsLogo =  [[UIImageView alloc] initWithFrame: CGRectMake(123.0f, 310.0f, 74.0f, 74.0f)];
    [contactsLogo setImage:[UIImage imageNamed: @"icon_contacts_74x74.png"]];
    [self.view addSubview:contactsLogo];
    
    syncButton = [[UIButton alloc]initWithFrame:CGRectMake(12.5f, 20.0f, 295.0f, 295.0f)];
	//[syncButton setButtonType:UIButtonTypeRoundedRect];
	[syncButton setBackgroundImage:[UIImage imageNamed: @"button_default.png"] forState:UIControlStateNormal];
	[syncButton setBackgroundImage:[UIImage imageNamed: @"button_onclick.png"] forState:UIControlEventTouchDown];
    
	[syncButton addTarget: self action:@selector(syncContactsAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:syncButton];

    // The "Sync All" label  
    allText = [[UILabel alloc] initWithFrame: CGRectMake(12.5f, 210.0f , 295.0f, 50.0f)];
    allText.textColor = [UIColor blackColor]; 
	allText.backgroundColor = [UIColor clearColor];
    allText.textAlignment = UITextAlignmentCenter;
    [allText setFont: large_font];
    [allText setText:NSLocalizedString(@"Sync Contacts", @"Sync Contacts")];  
    [self.view addSubview:allText];
    
    // The "Synchronization" and "To Cancel" Text
    synchronizeText = [[UILabel alloc] initWithFrame: CGRectMake(12.5f, 210.0f , 295.0f, 50.0f)];
    synchronizeText.textColor = [UIColor blackColor]; 
	synchronizeText.backgroundColor = [UIColor clearColor];
    synchronizeText.textAlignment = UITextAlignmentCenter;
    [synchronizeText setFont: large_font];
    [synchronizeText setText:NSLocalizedString(@"Syncing Contacts", @"Syncing Contacts")];  
    
    syncCancelText = [[UILabel alloc] initWithFrame: CGRectMake(12.5f, 235.0f , 295.0f, 50.0f)];
    syncCancelText.textColor = [UIColor blueColor]; 
	syncCancelText.backgroundColor = [UIColor clearColor];
    syncCancelText.textAlignment = UITextAlignmentCenter;
    [syncCancelText setFont: small_font];
    [syncCancelText setText:NSLocalizedString(@"CancelSyncText", @"CancelSyncText")];  
    
    // The status text for Contacts, with the last sync date
    NSString *contactsStatusTextValue =[self getLastSyncMessage];
    contactsStatusText = [[UILabel alloc] initWithFrame: CGRectMake(0.0f, 365.0f , 320.0f, 50.0f)];
	contactsStatusText.textColor = [UIColor blackColor];
	contactsStatusText.backgroundColor = [UIColor clearColor];
    contactsStatusText.textAlignment = UITextAlignmentCenter;
    [contactsStatusText setFont: medium_font];
    [contactsStatusText setText:contactsStatusTextValue];  
    [self.view addSubview:contactsStatusText];
    
    // The #1 white arrow, for the animation of the Contacts sync
    iconSyncDark[0] = [[UIImageView alloc] initWithFrame: CGRectMake(83.0f, 65.0f, 154.0f, 154.0f)];  
    [iconSyncDark[0] setImage:[UIImage imageNamed: @"icon_sync_154x154_frame01.png"]];
    
    iconSyncDark[1] = [[UIImageView alloc] initWithFrame: CGRectMake(83.0f, 65.0f, 154.0f, 154.0f)];  
    [iconSyncDark[1] setImage:[UIImage imageNamed: @"icon_sync_154x154_frame02.png"]];
    
    iconSyncDark[2] = [[UIImageView alloc] initWithFrame: CGRectMake(83.0f, 65.0f, 154.0f, 154.0f)];  
    [iconSyncDark[2] setImage:[UIImage imageNamed: @"icon_sync_154x154_frame03.png"]];
    
    iconSyncDark[3] = [[UIImageView alloc] initWithFrame: CGRectMake(83.0f, 65.0f, 154.0f, 154.0f)];  
    [iconSyncDark[3] setImage:[UIImage imageNamed: @"icon_sync_154x154_frame04.png"]];
    
    iconSyncDark[4] = [[UIImageView alloc] initWithFrame: CGRectMake(83.0f, 65.0f, 154.0f, 154.0f)];  
    [iconSyncDark[4] setImage:[UIImage imageNamed: @"icon_sync_154x154_frame05.png"]];
    
    iconSyncDark[5] = [[UIImageView alloc] initWithFrame: CGRectMake(83.0f, 65.0f, 154.0f, 154.0f)];  
    [iconSyncDark[5] setImage:[UIImage imageNamed: @"icon_sync_154x154_frame06.png"]];
    
    iconSyncDark[6] = [[UIImageView alloc] initWithFrame: CGRectMake(83.0f, 65.0f, 154.0f, 154.0f)];  
    [iconSyncDark[6] setImage:[UIImage imageNamed: @"icon_sync_154x154_frame07.png"]];
    
    iconSyncDark[7] = [[UIImageView alloc] initWithFrame: CGRectMake(83.0f, 65.0f, 154.0f, 154.0f)];  
    [iconSyncDark[7] setImage:[UIImage imageNamed: @"icon_sync_154x154_frame08.png"]];
    
    iconSyncDark[8] = [[UIImageView alloc] initWithFrame: CGRectMake(83.0f, 65.0f, 154.0f, 154.0f)];  
    [iconSyncDark[8] setImage:[UIImage imageNamed: @"icon_sync_154x154_frame09.png"]];
    
    iconSyncDark[9] = [[UIImageView alloc] initWithFrame: CGRectMake(83.0f, 65.0f, 154.0f, 154.0f)];  
    [iconSyncDark[9] setImage:[UIImage imageNamed: @"icon_sync_154x154_frame10.png"]];
    
    iconSyncDark[10] = [[UIImageView alloc] initWithFrame: CGRectMake(83.0f, 65.0f, 154.0f, 154.0f)];  
    [iconSyncDark[10] setImage:[UIImage imageNamed: @"icon_sync_154x154_frame11.png"]];
    
    iconSyncDark[11] = [[UIImageView alloc] initWithFrame: CGRectMake(83.0f, 65.0f, 154.0f, 154.0f)];  
    [iconSyncDark[11] setImage:[UIImage imageNamed: @"icon_sync_154x154_frame12.png"]];
    
    iconSyncDark[12] = [[UIImageView alloc] initWithFrame: CGRectMake(83.0f, 65.0f, 154.0f, 154.0f)];  
    [iconSyncDark[12] setImage:[UIImage imageNamed: @"icon_sync_154x154_frame13.png"]];
    
    iconSyncDark[13] = [[UIImageView alloc] initWithFrame: CGRectMake(83.0f, 65.0f, 154.0f, 154.0f)];  
    [iconSyncDark[13] setImage:[UIImage imageNamed: @"icon_sync_154x154_frame14.png"]];
    
    iconSyncDark[14] = [[UIImageView alloc] initWithFrame: CGRectMake(83.0f, 65.0f, 154.0f, 154.0f)];  
    [iconSyncDark[14] setImage:[UIImage imageNamed: @"icon_sync_154x154_frame15.png"]];
    
    iconSyncDark[15] = [[UIImageView alloc] initWithFrame: CGRectMake(83.0f, 65.0f, 154.0f, 154.0f)];  
    [iconSyncDark[15] setImage:[UIImage imageNamed: @"icon_sync_154x154_frame16.png"]];
    
    settingsButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Settings",@"Settings")
                                                      style:UIBarButtonItemStylePlain
                                                     target:self
                                                     action:@selector(settingsAction:)];
    
    [self.view addSubview:iconSyncDark[idx]];

    
    self.navigationItem.rightBarButtonItem = settingsButton;
}


- (void)disableAllButtons {
	[syncButton removeFromSuperview];
    self.navigationItem.rightBarButtonItem = nil;
}

- (void)enableAllButtons {
	[self.view addSubview:syncButton];
    [self.view addSubview:iconSyncDark[idx]];
    [self.view addSubview:allText];
    settingsButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Settings",@"Settings")
                                                      style:UIBarButtonItemStylePlain
                                                     target:self
                                                     action:@selector(settingsAction:)];
    self.navigationItem.rightBarButtonItem = settingsButton;
}

- (void)syncAllAction: (id)sender{
	[[UIController getInstance] syncAll];
}
- (void)syncContactsAction: (id)sender{
	[[UIController getInstance] sync:@"addressbook"];
}

- (void)settingsAction:(id)sender
{
	UIViewController *targetViewController = [[menuList objectAtIndex: 0] objectForKey:@"viewController"];
	[[self navigationController] pushViewController:targetViewController animated:YES];
}

- (void)stopAction:(id)sender
{
    //[[UIController getInstance] stopSyncContacts];
}

// Thread that handles the animation of the rotating arrows, fired by a timer
- (void)syncAnimation:(NSTimer *)timer
{
    [iconSyncDark[idx] removeFromSuperview];
    idx = ++syncArrow % 16;
    [self.view addSubview:iconSyncDark[idx]];

    if (syncContactText != nil) {
        [contactsStatusText setText:syncContactText];
        [syncContactText release];
        syncContactText = nil;
    }
}

- (void) startContactSyncArrowAnimation {
    // Start the timer task
    timer = [NSTimer scheduledTimerWithTimeInterval:0.3
                      target:self selector:@selector(syncAnimation:)
                      userInfo:nil repeats:YES];
}

- (void) cancelContactSyncArrowAnimation {

    [timer invalidate];
    [iconSyncDark[idx] removeFromSuperview];
}

- (void)updateContactSyncStatus:(NSString*)msg {
    
    [self updateContactSyncStatus: msg iconIdx:MAIN_SINGLE_VIEW_STATUS_ICON_NULL];
}

- (void)updateContactSyncStatus:(NSString*)msg iconIdx:(StatusSingleIconId) iconIdx {

    if (msg != nil) {
        [contactsStatusText setText:msg];
		[self.view addSubview:contactsStatusText];
    }
    if (iconIdx != MAIN_SINGLE_VIEW_STATUS_ICON_NULL) {
        [self.view addSubview:statusIcons[iconIdx]];
    }
}

// Sets the contact status string during a sync. Note that attempting to
// set status string via the updateContactSyncStatus during a sync does
// not work
- (void)updateContactSyncStatusDuringSync:(NSString*)msg {

    if (syncContactText)
    {
        [syncContactText release];
        syncContactText = nil;
    }
    syncContactText = msg;
}

// Adds the icons displayed during a sync all
- (void)setSyncAllView {
	[self setSyncContactsView];
}

// Adds the icons displayed during a sync all
- (void)setSyncContactsView {
    //[self.view addSubview:background];
	[self showStopButton];
}

- (void) showStopButton{

	[allText removeFromSuperview];
    [self.view addSubview:synchronizeText];
    [self.view addSubview:syncCancelText];
}

// This method removes all the icons that are set during sync
- (void)resetSyncIcons {
	[synchronizeText removeFromSuperview];
    [syncCancelText removeFromSuperview];
    [self.view addSubview:allText];
}

- (NSString*) getLastSyncMessage{
    int lastsync = [[FunambolAPI getInstance] getSyncSourceLastSyncDate:@"addressbook"];
    int today = time (NULL);
    
    NSDateComponents* todayDate = getDateComponentsFromDate1970(today);
    NSDateComponents* yesterdayDate = getDateComponentsFromDate1970((today - 86400));
    NSDateComponents* lastsyncDate = getDateComponentsFromDate1970(lastsync);
    
    if (lastsync == 0 ){
        return NSLocalizedString(@"Contacts never synched", @"Contacts never synched");
    }else if([todayDate year]   ==  [lastsyncDate year]     &&
             [todayDate month]  ==  [lastsyncDate month]    &&
             [todayDate day]    ==  [lastsyncDate day]){//today
        NSDate *lastSync = [NSDate dateWithTimeIntervalSince1970:lastsync];
        
        NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init]  autorelease];
        
        [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
        
        NSString* lastSyncText = [dateFormatter stringFromDate:lastSync];
        
        NSString* contactsStatusTextValue = NSLocalizedString(@"Last sync: ",@"Last sync: ");
        contactsStatusTextValue = [contactsStatusTextValue stringByAppendingString:NSLocalizedString(@"Today ",@"Today ")];
        lastSyncText = [contactsStatusTextValue stringByAppendingString:lastSyncText];
        return lastSyncText;
    }else if ([yesterdayDate year]   ==  [lastsyncDate year]     &&
              [yesterdayDate month]  ==  [lastsyncDate month]    &&
              [yesterdayDate day]    ==  [lastsyncDate day]){// yesterday
        NSDate *lastSync = [NSDate dateWithTimeIntervalSince1970:lastsync];
        NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init]  autorelease];
        
        [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
        
        //NSString* lastSyncText = [lastSync descriptionWithCalendarFormat:NSLocalizedString(@"Dateformat",@"%A, %I:%M%p") timeZone:nil locale:nil];
        NSString* lastSyncText = [dateFormatter stringFromDate:lastSync];
        
        NSString* contactsStatusTextValue = NSLocalizedString(@"Last sync: ",@"Last sync: ");
        contactsStatusTextValue = [contactsStatusTextValue stringByAppendingString:NSLocalizedString(@"Yesterday ",@"Yesterday ")];
        lastSyncText = [contactsStatusTextValue stringByAppendingString:lastSyncText];
        return lastSyncText;
    }else{
        
        NSDate *lastSync = [NSDate dateWithTimeIntervalSince1970:lastsync];
        NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init]  autorelease];
        
        [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
        
        [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
        
        NSString* lastSyncText = [dateFormatter stringFromDate:lastSync];
        
        NSString* contactsStatusTextValue = NSLocalizedString(@"Last sync: ",@"Last sync: ");
        lastSyncText = [contactsStatusTextValue stringByAppendingString:lastSyncText];
        return lastSyncText;
    }
    [yesterdayDate release];
    [todayDate release];
    [lastsyncDate release];
}

- (void) showMessage: (NSString*) messageText titleText: (NSString*) titleText{

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:titleText message:messageText
                                                   delegate:self cancelButtonTitle:NSLocalizedString(@"OK", @"OK") otherButtonTitles: nil];
    [alert show];
    [alert release];
    
    
}
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
     // the user clicked one of the OK/Cancel buttons
     if (buttonIndex == 0){
     }else{
         
     }
}

- (void) dealloc{
    [menuList release];
    
    [window release];
    [settingsButton release];
    [syncButton release];
	[contactsButton release];
	[stopButton release];
    [textView release];  
    [synchronizeText release];
    [syncCancelText release]; 
    [allText release];
    [contactsText release];
    [contactsStatusText release];
    [calendarText release];
    [calendarStatusText release];
    [tasksText release];
    [tasksStatusText release];
    [notesText release];
    [notesStatusText release];
    [textLabel release];
    [logo release];
    [background release];
    [buttonDarkBlue release];
    [buttonBlue release];
    [iconSyncAllBlue release];
    [timer release];
    [syncContactText release];

    [large_font release];
    [small_font release];
    [super dealloc];
}
@end


